1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/*!
A simple typing context based off a map
*/

use super::*;

/// A simple typing context based off a map
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MapTyCtx<T> {
    /// A map of unbound indices to types
    unbound: FxHashMap<u32, Option<TermId>>,
    /// A stack of bound indices
    bound: Vec<Option<TermId>>,
    /// The underlying context
    ctx: T,
}

impl<T: TyCtxMut> MapTyCtx<T> {
    /// Construct a new hash-map typing context
    pub fn new(ctx: T) -> MapTyCtx<T> {
        MapTyCtx {
            unbound: FxHashMap::default(),
            bound: Vec::new(),
            ctx,
        }
    }

    /// Get the entry for a variable
    #[inline]
    fn get_entry<'a>(
        unbound: &'a FxHashMap<u32, Option<TermId>>,
        bound: &'a Vec<Option<TermId>>,
        ix: u32,
    ) -> Option<&'a TermId> {
        if let Some(ix) = Self::get_bound_ix(bound, ix) {
            return bound.get(ix).unwrap().as_ref();
        }
        unbound.get(&(ix - bound.len() as u32))?.as_ref()
    }

    /// Allocate an entry for a variable
    #[inline]
    fn alloc_entry<'a>(
        unbound: &'a mut FxHashMap<u32, Option<TermId>>,
        bound: &'a mut Vec<Option<TermId>>,
        ix: u32,
    ) -> &'a mut Option<TermId> {
        if let Some(ix) = Self::get_bound_ix(bound, ix) {
            return bound.get_mut(ix).unwrap();
        }
        Self::alloc_unbound(unbound, bound, ix)
    }

    /// Allocate an unbound entry for a variable
    #[inline]
    fn alloc_unbound<'a>(
        unbound: &'a mut FxHashMap<u32, Option<TermId>>,
        bound: &'a mut Vec<Option<TermId>>,
        ix: u32,
    ) -> &'a mut Option<TermId> {
        unbound.entry(ix - bound.len() as u32).or_default()
    }

    /// Get the bound index for a variable
    #[inline]
    fn get_bound_ix(bound: &Vec<Option<TermId>>, ix: u32) -> Option<usize> {
        let last = bound.len().checked_sub(1)?;
        let rev_ix = last.checked_sub(ix as usize)?;
        Some(rev_ix)
    }

    /// Get the amount to shift an entry by
    fn get_shift(&self, ix: u32) -> Result<i32, Error> {
        i32::try_from((ix as usize).min(self.bound.len() as usize))
            .map_err(|_| Error::ParameterOverflow)
    }
}

impl<T> TyCtxMut for MapTyCtx<T>
where
    T: TyCtxMut,
{
    type ConsCtx = T::ConsCtx;
    type TermEqCtx = T::TermEqCtx;
    type MaxDeref = Self;

    #[inline]
    fn infer(&mut self, ix: u32) -> Option<TermId> {
        let shift = self.get_shift(ix).ok()?;
        Self::get_entry(&self.unbound, &self.bound, ix)?
            .shifted(shift, 0, self.ctx.cons_ctx())
            .ok()
    }

    fn constrain(&mut self, ix: u32, annot: &TermId) -> Result<Option<bool>, Error> {
        let shift = self.get_shift(ix)?;
        let entry = Self::alloc_entry(&mut self.unbound, &mut self.bound, ix);
        if let Some(raw) = entry {
            let infer = raw.shift_cow(shift, 0, self.ctx.cons_ctx())?;
            Ok(annot.is_subtype_in(&*infer, self.ctx.eq_ctx()))
        } else {
            let shift_down = -i32::try_from(shift).map_err(|_| Error::ParameterOverflow)?;
            let ctx = &mut self.ctx;
            let shifted = annot
                .shift(shift_down, 0, ctx.cons_ctx())?
                .unwrap_or_else(|| annot.consed(ctx.cons_ctx()));
            *entry = Some(shifted);
            Ok(Some(true))
        }
    }

    fn check(&mut self, ix: u32, annot: &TermId) -> Result<Option<bool>, Error> {
        let shift = self.get_shift(ix)?;
        if let Some(raw) = Self::get_entry(&self.unbound, &self.bound, ix) {
            let infer = raw.shift_cow(shift, 0, self.ctx.cons_ctx())?;
            Ok(annot.is_subtype_in(&*infer, self.ctx.eq_ctx()))
        } else {
            Ok(Some(true))
        }
    }

    fn push_param(&mut self, param_ty: Option<&TermId>) -> Result<(), Error> {
        self.ctx.push_param(param_ty)?;
        self.bound
            .push(param_ty.shifted(1, 0, self.ctx.cons_ctx())?);
        Ok(())
    }

    fn pop_param(&mut self) -> Result<(), Error> {
        if self.bound.len() == 0 {
            return Err(Error::ParameterUnderflow);
        }
        self.ctx.pop_param()?;
        self.bound.pop();
        Ok(())
    }

    fn global_tyck_mask(&self, _filter: VarFilter) -> L4 {
        L4::True
    }

    fn var_tyck_mask(&self, filter: VarFilter) -> L4 {
        self.ctx.global_tyck_mask(filter).intersection(L4::True)
    }

    fn annot_tyck_mask(&self, _filter: VarFilter) -> L4 {
        L4::True
    }

    fn approx_tyck(&self, flags: TyckFlags, filter: VarFilter) -> Option<bool> {
        //TODO: better filter specificity
        if (self.unbound.is_empty() && self.bound.is_empty()) || filter.is_empty() {
            self.ctx.approx_tyck(flags, filter)
        } else {
            None
        }
    }

    #[inline]
    fn approx_global_tyck(&self, flags: TyckFlags, _filter: VarFilter) -> Option<bool> {
        flags.get_flag(GlobalTyck).truth_value()
    }

    #[inline]
    fn approx_var_tyck(&self, flags: TyckFlags, filter: VarFilter) -> Option<bool> {
        //TODO: better filter specificity
        if (self.unbound.is_empty() && self.bound.is_empty()) || filter.is_empty() {
            self.ctx.approx_tyck(flags, filter)
        } else {
            None
        }
    }

    fn approx_annot_tyck(&self, flags: TyckFlags, filter: VarFilter) -> Option<bool> {
        //TODO: better filter specificity
        if (self.unbound.is_empty() && self.bound.is_empty()) || filter.is_empty() {
            self.ctx.approx_tyck(flags, filter)
        } else {
            None
        }
    }

    #[inline]
    fn ty_ctx_base(&self) -> u32 {
        self.bound.len() as u32
    }

    #[inline]
    fn reset_unbound(&mut self) -> Result<(), Error> {
        self.unbound.clear();
        Ok(())
    }

    #[inline]
    fn cons_ctx(&mut self) -> &mut Self::ConsCtx {
        self.ctx.cons_ctx()
    }

    #[inline]
    fn eq_ctx(&mut self) -> &mut Self::TermEqCtx {
        self.ctx.eq_ctx()
    }

    #[inline]
    fn ctx(&mut self) -> &mut Self::MaxDeref {
        self
    }
}